/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.command.util;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import jp.aist.gtrc.plus.reserve.ReserveException;
import jp.aist.gtrc.plus.reserve.ReserveServer;
import jp.aist.gtrc.plus.scheduler.util.AppOption;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;
import jp.aist.gtrc.plus.scheduler.util.AppOption.AppOptionException;


public class PlusReserveCommand {

	protected static ReserveServer getReserveServer(PlusCommandOptions options) throws ReserveException  {

		if (System.getSecurityManager() == null)
			System.setSecurityManager(new PlusSecurityManager());

		String hostName = options.getReserveServerHost();
		int rmiPort = options.getRMIPort();
		/*
		 * getRegistry(host, port, csf) can use original RMIClientSocketFactroy
		 * but it's used only for connection to server registry,
		 * not used for RMI server (ReserveServerRMIImpl etc).
		 * So we use default ClientSocketFactroy (not specify csf).
		 */
		try {
			Registry registry = LocateRegistry.getRegistry(
					hostName, rmiPort);
			ReserveServer server = (ReserveServer)registry.lookup(
					ReserveServer.RMI_OBJECT_NAME);
			return server;
		} catch (Exception e) {
			throw new ReserveException("cannot connect to " + hostName + ":" + rmiPort
					+ ". PluS is not running or access denied.");
		}

	}

	protected static final String getMyname() {

		return System.getProperty("user.name");

	}

	protected static final void showCommandHelp(AppOption opt, Exception e) {

		showException(e);
		opt.showHelp();

	}

	protected static final void showException(Exception e) {

		if (e instanceof AppOptionException) {
			AppOptionException ae = (AppOptionException)e;
			if (ae.isHelpRequested()) {
				// "-h" or something is specified, it's not problem.
				return;
			}
		}

		String s = e.getMessage();
		if (TextUtil.isValid(s)) {
			System.err.print("ERROR: " + s);
			if (s.endsWith("\n") == false) {
				System.err.println("");
			}
		} else {
			e.printStackTrace();
		}

	}

}
